import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { pinyin } from 'pinyin-pro'
import { localConsoleRobotApi,  type RoboSimpletInfo } from '@/api/zyApi'

export const useSelectTree = () => {
    interface roborOptions {
        label: string
        pinyinSort: string
        children: RoboSimpletInfo[]
    }
    // 组件统计数据
    const summaryData = reactive<{
        label: string
        value: number
    }[]>([
        {
            label: '机器人数量(台)',
            value: 0
        }, {
            label: '在线数量(台)',
            value: 0
        }, {
            label: '离线数量(台)',
            value: 0
        }, {
            label: '已禁用数量(台)',
            value: 0
        }
    ])

    const choseRobot = ref(false)
    const robotPinyinOption = ref<selectTreeOption[]>([])
    const robotOption = reactive<roborOptions[]>([])
    interface selectTreeOption {
        label?: string
        value?: string
        pinyinSort?: string
        id: string
        children?: selectTreeOption[]
    }

    //判断鼠标点击是否再指定dom中，否则关闭机器人下拉框
    const handleClickOutside = (e: MouseEvent) => {
        const isInput = e.target instanceof HTMLElement && e.target.closest('.robotSelect');
        const isMenu = e.target instanceof HTMLElement && e.target.closest('#robotList');
        if (!isInput && !isMenu) {
            choseRobot.value = false
        }
    }
    //开启机器人下拉框
    const openOption = async () => {
        choseRobot.value = true
    }

    // 获取全部机器人列表
    const getRobotSimpList = () => {
        localConsoleRobotApi.GetRobotInfos({
            PageIndex: 1,
            /** 每页显示条数 */
            PageSize: 100,
        }).then(({ Datas, TotalNumber }) => {
            console.log(Datas)
            const isOnlineCount = Datas.filter((item: any) => item.IsOnline).length
            const isOfflineCount = Datas.filter((item: any) => !item.IsOnline).length
            const isDisabledCount = Datas.filter((item: any) => item.IsDisable).length
            summaryData.splice(0, summaryData.length,
                {
                    label: '机器人数量(台)',
                    value: TotalNumber
                }, {
                label: '在线数量(台)',
                value: isOnlineCount
            }, {
                label: '离线数量(台)',
                value: isOfflineCount
            }, {
                label: '已禁用数量(台)',
                value: isDisabledCount
            }
            )
            robotOption.splice(0, robotOption.length, ...categorizeRobots(Datas))
            setPinyinSort(robotOption)
            console.log(robotOption, 'robotOption')
        })
    }
    // 机器人按照标签分组
    const categorizeRobots = (robots: any) => {
        const categories = new Map();
        // 初始化"其他"分类
        categories.set('其他', {
            label: '其他',
            children: [],
            pinyinSort: ''
        });

        robots.forEach((robot: any) => {
            const hasTags = robot.Tags?.length > 0;

            if (hasTags) {
                robot.Tags.forEach((tag: any) => {
                    const label = tag.Name;
                    if (!categories.has(label)) {
                        categories.set(label, {
                            label,
                            children: [],
                            pinyinSort: '' // 可扩展拼音排序逻辑
                        });
                    }
                    categories.get(label).children.push(robot);
                });
            } else {
                categories.get('其他').children.push(robot);
            }
        });

        return Array.from(categories.values());
    }

    const setPinyinSort = (datas: roborOptions[]) => {
        let arr: selectTreeOption[] = []
        datas.forEach((item: any) => {
            console.log(item, 'tes')
            let pinyinStr = pinyin(item.label.slice(0, 1), { toneType: 'none' }).charAt(0).toUpperCase()
            console.log(pinyinStr, 'pinyinStr')
            if (arr.length === 0) {
                arr.push({
                    label: pinyinStr,
                    id: pinyinStr,
                    pinyinSort: pinyinStr,
                    children: [{
                        ...item
                    }]
                })
            } else {
                // 使用 for 循环确保数组遍历
                let has = false;
                for (let i = 0; i < arr.length; i++) {
                    if (pinyinStr === arr[i].pinyinSort) {
                        arr[i].children?.push({ ...item });
                        has = true;
                        break; // 若只需匹配第一个分组，提前终止循环
                    }
                }
    
                // 同步判断 has 的值
                if (!has) {
                    arr.push({
                        label: pinyinStr,
                        pinyinSort: pinyinStr,
                        id: pinyinStr,
                        children: [item]
                    });
                }
            }
        })
        robotPinyinOption.value = [...robotPinyinOption.value, ...sortChinese(arr)]
        console.log(robotPinyinOption.value, 'robotPinyinOption.value')
    }
    
    const sortChinese = (arr: selectTreeOption[]) => {
        arr.sort((a, b) => {
            if (a.pinyinSort && b.pinyinSort) {
                return a.pinyinSort.localeCompare(b.pinyinSort);
            }
            return 0;
        });
        return arr;
    };

    onMounted(() => {
        getRobotSimpList()
        //监听鼠标点击事件
        // window.addEventListener('click', handleClickOutside)
    })

    onUnmounted(() => {
        //注销鼠标点击事件
        // window.removeEventListener('click', handleClickOutside)
    })

    return {
        openOption,
        robotPinyinOption,
        choseRobot,
        summaryData
    }
}